package com.web.system.action;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ModelDriven;
import com.util.BaseActionUtil;
import com.util.JsonUtil;
import com.web.system.po.RolePo;
import com.web.system.po.TreeMenuPo;
import com.web.system.po.UserPo;
import com.web.system.service.RoleService;
import com.web.system.service.TreeMenuService;
import com.web.system.service.UserService;

@Controller @Scope("prototype") 
@ParentPackage(value = "struts-default")
@Namespace(value = "/")
@Action(value = "treeAction",results={
		@Result(name="send",location="/file/send.jsp"),
		@Result(name="input",location="/file/send.jsp")
})
public class TreeMenuAction extends BaseActionUtil implements ModelDriven<TreeMenuPo>{
	
	private static final long serialVersionUID = -5242014974594813628L;
	@Resource
	private TreeMenuService treeMenuService;
	@Resource
	private UserService userService;
	@Resource
	private RoleService roleService;
	
	
	private TreeMenuPo treeMenuPo;

	public TreeMenuPo getModel() {
		// TODO Auto-generated method stub
		treeMenuPo = new TreeMenuPo();
		return treeMenuPo;
	}
	
	/**
	 * 菜单名是否存在
	 * @return
	 * @throws Exception
	 */
	public String isExistMenu() throws Exception{
		
		String name = request.getParameter("name");
		out.print(treeMenuService.isExistMenu(name) ? "0" : "1");
		out.flush();
		out.close();
		return NONE;
	}
	
	/**
	 * 动态的同步树形组件
	 * 
	 * @return
	 * @throws Exception
	 */
	public String syncMenu() throws Exception {
		String type = request.getParameter("type");
		UserPo user = (UserPo) session.getAttribute("user");
		List<Map<String, Object>> treeList = treeMenuService.syncMenu(request,user,type);
		String jsonStr = JsonUtil.objectToStr(treeList);
		out.print(jsonStr);
		out.flush();
		out.close();
		return NONE;
	}

	/**
	 * 异步动态树
	 * @return
	 * @throws Exception
	 */
	public String getMenuIdsByRoleId() throws Exception {
		String roleId = request.getParameter("roleId");
		RolePo rolePo = roleService.getRoleByRoleId(Integer.parseInt(roleId));
		Set<TreeMenuPo> treeMenuPos = rolePo.getTreeMenuPos();
		StringBuffer menuIds = new StringBuffer();
		for (TreeMenuPo treeMenuPo : treeMenuPos) {
			menuIds.append(treeMenuPo.getId());
			menuIds.append(",");
		}
		menuIds.substring(0, menuIds.length() - 1);
		String jsonStr = JsonUtil.objectToStr(menuIds);
		out.print(jsonStr);
		out.flush();
		out.close();
		return NONE;
	}
	
	/**
	 * 获取menu菜单列表
	 * @return
	 * @throws Exception
	 */
	public String getMenuList () throws Exception {

		//分页部分
		int page = Integer.parseInt(request.getParameter("page"));
		int pageSize = Integer.parseInt(request.getParameter("rows"));
		int first = pageSize * (page - 1);
		String order = request.getParameter("order");
		String sort = request.getParameter("sort");
		
		//搜索部分
		String sql = "";
		if(treeMenuPo.getId() != null && !"".equals(treeMenuPo.getId()) && !"null".equals(treeMenuPo.getId())){
			sql += " and id like '" + treeMenuPo.getId() + "%'" ;
		}
		if(treeMenuPo.getMenuName() != null && !"".equals(treeMenuPo.getMenuName()) && !"null".equals(treeMenuPo.getMenuName())){
			sql += " and menuName like '%" + treeMenuPo.getMenuName() + "%'" ;
		}
		if(treeMenuPo.getMenuHref() != null && !"".equals(treeMenuPo.getMenuHref()) && !"null".equals(treeMenuPo.getMenuHref())){
			sql += " and menuHref like '%" + treeMenuPo.getMenuHref() + "%'" ;
		}
		if(treeMenuPo.getMenuTarget() != null && !"".equals(treeMenuPo.getMenuTarget()) && !"null".equals(treeMenuPo.getMenuTarget())){
			sql += " and menuTarget like '%" + treeMenuPo.getMenuTarget() + "%'" ;
		}
		if(treeMenuPo.getParentId()!= null && !"".equals(treeMenuPo.getParentId()) && !"null".equals(treeMenuPo.getParentId())){
			sql += " and parentId = '" + treeMenuPo.getParentId() + "'" ;
		}
		if(treeMenuPo.getGrade() != null && !"".equals(treeMenuPo.getGrade()) && !"null".equals(treeMenuPo.getGrade())){
			sql += " and grade = '" + treeMenuPo.getGrade() + "'" ;
		}
		if(treeMenuPo.getIconCls() != null && !"".equals(treeMenuPo.getIconCls()) && !"null".equals(treeMenuPo.getIconCls())){
			sql += " and iconCls like '%" + treeMenuPo.getIconCls() + "%'" ;
		}
		if(treeMenuPo.getIsLeaf() != null && !"".equals(treeMenuPo.getIsLeaf()) && !"null".equals(treeMenuPo.getIsLeaf())){
			sql += " and isLeaf = '" + treeMenuPo.getIsLeaf() + "'" ;
		}
		//组合最终sql语句
		StringBuffer queryStringBuffer = new StringBuffer();
		queryStringBuffer.append("FROM TreeMenuPo where 1=1 ");
		queryStringBuffer.append(sql);
		queryStringBuffer.append(" ORDER BY  ");
		queryStringBuffer.append(sort);
		queryStringBuffer.append(" ");
		queryStringBuffer.append(order);
        List<TreeMenuPo> treeMenuPos = treeMenuService.getMenuList(queryStringBuffer.toString(), first, pageSize);
        Map<String, Object> mapJson = new HashMap<String, Object>();
        int total = treeMenuService.getTotal(sql);
        mapJson.put("total", total);
        mapJson.put("rows", treeMenuPos);
        out.print(JsonUtil.objectToStr(mapJson, new String[]{"roleBeans"}));
        out.flush();
        out.close();
		return NONE;
	}
	
	/**
	 * 添加菜单
	 * @return
	 * @throws Exception
	 */
	public String addMenu() throws Exception {
		
		String parentId = treeMenuPo.getParentId();
		if(parentId == null || "".equals(parentId) || "null".equalsIgnoreCase(parentId)){
			treeMenuPo.setParentId("0");
		} else {
			if(treeMenuService.isLeafMenuId(parentId)){
				out.print("0");//父结点不能为叶子节点
				out.flush();
				out.close();
				return NONE;
			}
		}
		String menuId = treeMenuService.getAddMenuIdByParentId(treeMenuPo.getParentId());
		treeMenuPo.setId(menuId);
		int grade = treeMenuService.getAddGradeByParentId(treeMenuPo.getParentId());
		treeMenuPo.setGrade(grade);
		out.print(treeMenuService.saveOrUpdateMenu(treeMenuPo) ? "1" : "-1");
		out.flush();
		out.close();
		return NONE;
	}
	
	/**
	 * 根据menuid获取menu
	 * @return
	 * @throws Exception
	 */
	public String getMenuByMenuId() throws Exception {
		
		String id = request.getParameter("id");
		TreeMenuPo treeMenuPo = treeMenuService.getMenuByMenuId(id);
		Map<String, Object> map = new HashMap<String, Object>();
		if("0".equals(treeMenuPo.getParentId())){
			map.put("parentMenuName",null);
		}else{
			TreeMenuPo treeMenuPo2 = treeMenuService.getMenuByMenuId(treeMenuPo.getParentId());
			map.put("parentMenuName",treeMenuPo2.getMenuName());
		}
		treeMenuPo.setRoleBeans(null);
		map.put("treeMenuPo", treeMenuPo);
		String jsonString;
		jsonString = JsonUtil.objectToStr(map);
		out.print(jsonString);
		out.flush();
		out.close();
		return NONE;
	}
	
	/**
	 * 修改菜单
	 * @return
	 * @throws Exception
	 */
	public String updateMenu() throws Exception {
		TreeMenuPo treeMenu = treeMenuService.getMenuByMenuId(treeMenuPo.getId());
		if(treeMenu.getParentId().equals(treeMenuPo.getParentId())){
			treeMenu.setIconCls(treeMenuPo.getIconCls());
			treeMenu.setMenuHref(treeMenuPo.getMenuHref());
			treeMenu.setMenuName(treeMenuPo.getMenuName());
			treeMenu.setMenuTarget(treeMenuPo.getMenuTarget());
			treeMenu.setIsLeaf(treeMenuPo.getIsLeaf());
			out.print(treeMenuService.saveOrUpdateMenu(treeMenu) ? "1" : "-1");
		} else{
			String parentId = treeMenuPo.getParentId();
			if(parentId == null || "".equals(parentId) || "null".equalsIgnoreCase(parentId)){
				treeMenuPo.setParentId("0");
			}else{
				if(treeMenuService.isLeafMenuId(parentId)){
					out.print("0");//父结点不能为叶子节点
					out.flush();
					out.close();
					return NONE;
				}
			}
			String menuId = treeMenuService.getAddMenuIdByParentId(treeMenuPo.getParentId());
			treeMenuPo.setId(menuId);
			int grade = treeMenuService.getAddGradeByParentId(treeMenuPo.getParentId());
			treeMenuPo.setGrade(grade);
			//System.out.println();
			out.print(treeMenuService.updateAndDeleteMenu(treeMenu,treeMenuPo) ? "1" : "-1");
		}
		out.flush();
		out.close();
		return NONE;
	}
	
	public String  deleteMenu() throws Exception{
		String menuIds = request.getParameter("menuIds");
		String [] ids = menuIds.split(",");
		for (int i = 0; i < ids.length; i++) {
			TreeMenuPo treeMenu = treeMenuService.getMenuByMenuId(ids[i]);
			//System.out.println(rolePo.getRoleName());
			if(treeMenu.getRoleBeans().size() > 0){
				System.out.println("ddd " + treeMenu.getRoleBeans().size());
				out.print("0");
				out.flush();
				out.close();
				return NONE;
			}
		}
		String sql = "DELETE from TreeMenuPo WHERE id IN (" + menuIds + ")";
		out.print(treeMenuService.executeUpdates(sql));
		out.flush();
		out.close();
		return NONE;
	}
	

	public String execute() throws Exception {
		// TODO Auto-generated method stub
		return null;
	}


}
